import { BaseDatabase, DatabaseConfig } from './base';
import SQLiteDatabase from './sqlite';
import MongoDatabase from './mongodb';

let singleton: BaseDatabase | null = null;

export function createDatabase(config?: Partial<DatabaseConfig>): BaseDatabase {
  const type = (config?.type || (process.env.DB_TYPE as any) || 'sqlite') as 'sqlite' | 'mongodb';

  if (singleton && singleton.isConnected()) {
    return singleton;
  }

  const finalConfig: DatabaseConfig = {
    type,
    connectionString: config?.connectionString || (type === 'sqlite' ? process.env.SQLITE_PATH : process.env.MONGODB_URI),
    options: config?.options || (type === 'mongodb' ? { dbName: process.env.MONGODB_DB || 'aigc' } : {}),
  } as DatabaseConfig;

  singleton = type === 'sqlite' ? new SQLiteDatabase(finalConfig) : new MongoDatabase(finalConfig);
  return singleton;
}

export async function getDb(config?: Partial<DatabaseConfig>): Promise<BaseDatabase> {
  const db = createDatabase(config);
  if (!db.isConnected()) await db.connect();
  return db;
}

export * from './base';